//
//  AceListVC.m
//  APP_login
//
//  Created by edz on 7/27/21.
//  Copyright © 2021 baicai. All rights reserved.
//
#import "BZKTools.h"
#import "AceListVC.h"
#import "AceListCell.h"
#import "AceListHeader.h"
#import "AceCellModel.h"

#import "Masonry.h"
#import "AFNetworking.h"

@interface AceListVC ()<UITableViewDelegate, UITableViewDataSource , UIGestureRecognizerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *titlable;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, assign) BOOL isAdd;
@property (nonatomic, assign) BOOL isdrown;
@end

@implementation AceListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    _modelArray = [NSMutableArray array];
    
    _titlable = [UILabel new];
    _titlable.text = @"今日牛人榜";
    _titlable.textColor = [UIColor whiteColor];
    _titlable.font = [UIFont systemFontOfSize:20];
    _titlable.textAlignment = NSTextAlignmentCenter;
    _isAdd = NO;
    
    UIImage *image = [self scaleToSize:[UIImage imageNamed:@"WhiteLeftTriangel"] size:CGSizeMake(35, 35)];
    UIButton *button = [UIButton systemButtonWithImage:image target:self action:@selector(leftButtonClick)];
    button.tintColor = [UIColor whiteColor];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    _bgView = [UIView new];
    [self.view addSubview:_bgView];
    _bgView.backgroundColor = [UIColor colorWithRed:249/255.0f green:79/255.0f blue:76/255.0f alpha:1.0f];
    [_bgView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(350);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style: UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(100);
        make.right.left.mas_equalTo(0);
        make.bottom.mas_equalTo(50);
    }];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.layer.cornerRadius = 7;
    _tableView.layer.masksToBounds = YES;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight =  UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 200;
    [_tableView registerClass:[AceListCell class] forCellReuseIdentifier:NSStringFromClass([AceListCell class])];
    [_tableView registerClass:[AceListHeader class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([AceListHeader class])];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(viewPan:)];
    [_tableView addGestureRecognizer:pan];
    pan.delegate = self;
    [self loadData];
}

-(void)loadData{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *dict = @{@"page": @"0", @"userID": @"15909993", @"userKey":@"4Gebhx4g0IainRD1Rwfyv3uLi6PJ8aG3"};
    [manager POST:@"http://101.37.27.140:8083/content/niuren-top" parameters:dict progress:^(NSProgress *_Nonnull downloadProgress){
        
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject){
//        NSLog(@"%@", responseObject);
        NSMutableArray *array= [AceCellModel arrayOfModelsFromDictionaries:[responseObject objectForKey:@"userList"] error:nil];
        [self.modelArray addObjectsFromArray:array];
//        NSLog(@"%@", array);
    } failure:^(NSURLSessionDataTask *_Nonnull task, NSError *_Nonnull error){
        NSLog(@"出错了%@", error);
    }];
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

-(void) scrollViewDidScroll:(UIScrollView *)scrollView{
    //添加titleView
    if (!_isAdd) {
        self.navigationItem.titleView = _titlable;
        _isAdd = YES;
    }
    CGFloat y = _tableView.contentOffset.y;
    //下拉禁止弹动
    if (y <= 0) {
        _tableView.bounces = NO;
    }else{
        _tableView.bounces = YES;
    }
    //下拉titleView透明
    if (y>= 0 && y<= 70 ) {
        self.navigationItem.titleView.alpha = y/70;
    }
    if (y > 70) {
        self.navigationItem.titleView.alpha = 1;
    }
    //是否tableview动画
    if (y == 0) {
        _isdrown = YES;
    }else{
        _isdrown = NO;
    }
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.modelArray.count;
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AceListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AceListCell class])];
    if (cell) {
        cell = [[AceListCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:NSStringFromClass([AceListCell class])];
    }
    AceListModel *model = self.modelArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    AceListHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([AceListHeader class])];
    if (header) {
        header = [[AceListHeader alloc] initWithReuseIdentifier:NSStringFromClass([AceListHeader class])];
    }
    return header;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 80;
}

- (void) viewPan:(UIPanGestureRecognizer *)pan{
    CGPoint point = [pan translationInView:self.view];
    if (point.y >=0 && point.y <= 150 && _isdrown) {
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make){
            make.top.mas_equalTo(100+point.y);
        }];
        [self.tableView layoutIfNeeded];
    }
    if (pan.state == UIGestureRecognizerStateEnded) {
        [UIView animateWithDuration:0.5 animations:^(void){
           [self.tableView mas_updateConstraints:^(MASConstraintMaker *make){
               make.top.mas_equalTo(100);
           }];
           [self.tableView layoutIfNeeded];
        } completion:^(BOOL finish){}];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer;{
    return YES;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void) leftButtonClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
     // 创建一个bitmap的context
     // 并把它设置成为当前正在使用的context
     UIGraphicsBeginImageContext(size);
     // 绘制改变大小的图片
     [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
     // 从当前context中创建一个改变大小后的图片
     UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
     // 使当前的context出堆栈
     UIGraphicsEndImageContext();
     // 返回新的改变大小后的图片
     return scaledImage;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
